package com.jm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jm.domain.LoginUser;
import com.jm.domain.User;
import com.jm.mapper.MenuMapper;
import com.jm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 重构查询用户的操作，使得从数据库中查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    public UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //如果查询不到，就抛出异常给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        //根据用户查询权限信息，添加到LoginUser中
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        //List<String> list =new ArrayList<>(Arrays.asList("test","admin"));
        //封装到成UserDetails对象返回
        return new LoginUser(user,list);
    }
}
